import csv
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkinter import *


# 登录窗口
def login(master):
    # 执行登录
    def dologin():
        user = entryuser.get()
        passwd = entrypasswd.get()
        admin = "lizj"
        admin_passwd = "123456"
        if user == admin and passwd == admin_passwd:
            login_frame.destroy()
        else:
            messagebox.showinfo("Warning", "账号或密码错误！")

    login_frame = tk.Frame(master)
    login_frame.grid(padx=15, pady=15)
    # 创建关联字符变量
    varuser = StringVar(login_frame, value='')
    varpasswd = StringVar(login_frame, value='')
    # 将俩个标签分别布置在第一行、第二行
    tk.Label(login_frame, text="账号：").grid(row=0)
    tk.Label(login_frame, text="密码：").grid(row=1)
    # 创建文本框组件，同时设置关联的变量
    #    用户名entryname
    #    密码entryinprice
    entryuser = Entry(login_frame, textvariable=varuser)
    entryuser.grid(row=0, column=1, padx=10, pady=5)
    entrypasswd = Entry(login_frame, show='*', textvariable=varpasswd)
    entrypasswd.grid(row=1, column=1, padx=10, pady=5)
    # 使用 grid()的函数来布局，并控制按钮的显示位置
    tk.Button(login_frame, text="登录", width=10, command=dologin).grid(row=3, column=0, sticky="w", padx=10, pady=5)
    tk.Button(login_frame, text="退出", width=10, command=login_frame.quit).grid(row=3, column=1, sticky="e", padx=10,
                                                                               pady=5)
    return login_frame


# 下面就是用户登录成功了应该出现的页面
def index(master):
    index_frame = tk.Frame(master)
    index_frame.grid()


def show():  # 展示商品信息
    window_show = tk.Tk()
    window_show.title("商品信息")
    width = 500
    height = 500
    window_show.resizable(False, False)
    window_show.geometry("{:}x{:}".format(width, height))
    # 创建一个滚动条控件，默认为垂直方向
    sbar1 = Scrollbar(window_show)
    # 将滚动条放置在右侧，并设置当窗口大小改变时滚动条会沿着垂直方向延展
    sbar1.pack(side=RIGHT, fill=Y)
    # 创建水平滚动条，默认为水平方向,当拖动窗口时会沿着X轴方向填充
    sbar2 = Scrollbar(window_show, orient=HORIZONTAL)
    sbar2.pack(side=BOTTOM, fill=X)

    # 刷新数据
    def refresh():
        tree.delete(*tree.get_children())
        with open('goods.csv', newline='')as f:
            # 读取csv中商品信息并创建类
            f_csv = csv.reader(f)
            headers = next(f_csv)
            rows = [i for i in f_csv]
        for i in rows:
            if float(i[4]) == 10:
                i[4] = "无"
            tree.insert("", END, values=i)

    # 创建表格添加数据
    with open('goods.csv', newline='')as f:
        # 读取csv中商品信息并创建类
        f_csv = csv.reader(f)
        headers = next(f_csv)
        rows = [i for i in f_csv]
    tree = ttk.Treeview(window_show, columns=headers, show="headings",
                        displaycolumns=['id', 'name', 'out_price', 'discount', 'inventory'], height=20)
    tree.heading('id', text="商品编号")
    tree.heading('name', text="商品名称")
    tree.heading('out_price', text="销售单价")
    tree.heading('discount', text="折扣")
    tree.heading('inventory', text="库存")
    tree.column('id', width=100, anchor=CENTER)
    tree.column('name', width=100, anchor=CENTER)
    tree.column('out_price', width=100, anchor=CENTER)
    tree.column('discount', width=100, anchor=CENTER)
    tree.column('inventory', width=100, anchor=CENTER)
    for i in rows:
        if float(i[4]) == 10:
            i[4] = "无"
        tree.insert("", END, values=i)
    tree.pack(expand=0, fill=Y)

    # 刷新按钮
    tk.Button(window_show, text="刷新数据", command=refresh).place(x=370, y=435, height=40, width=100)

    # 使用 command 关联控件的 yview、xview方法
    sbar1.config(command=tree.yview)
    sbar2.config(command=tree.xview)
    window_show.mainloop()


def buy():
    window_buy = tk.Tk()
    window_buy.title("商品购买")
    width = 500
    height = 500
    window_buy.geometry("{:}x{:}".format(width, height))
    window_buy.resizable(False, False)

    # 创建关联字符变量
    varid = IntVar(window_buy, value='')
    varunm = IntVar(window_buy, value='')
    # 创建标签组件
    Label(window_buy, text="商品编号：", font="微软雅黑").place(x=30, y=10, height=40, width=100)
    Label(window_buy, text="购买数量：", font="微软雅黑").place(x=30, y=60, height=40, width=100)
    # 创建文本框组件，同时设置关联的变量
    #    商品编号entryid
    #    购买数量entrynum
    entryid = Entry(window_buy, textvariable=varid)
    entryid.place(x=150, y=10, height=40, width=200)
    entrynum = Entry(window_buy, textvariable=varunm)
    entrynum.place(x=150, y=60, height=40, width=200)

    def dobuy():
        try:
            id = int(entryid.get())
            num = int(entrynum.get())
        except:
            messagebox.showinfo("Warning", "非法输入！")
        else:
            with open('goods.csv', newline='')as f:
                # 读取csv中商品信息
                f_csv = csv.reader(f)
                goods = [row for row in f_csv]

            if id > len(goods) - 1:
                messagebox.showinfo("Warning", "暂无该商品！")
            else:
                n = 0
                for good in goods:
                    if good[0] == str(id):
                        total = float(good[3]) * num * 0.1 * float(good[4])
                        global pay
                        pay += total
                        tree.insert("", END, values=[good[1], good[3], num, total])
                        global buyed
                        buyed[n][5] = int(goods[n][5]) - num
                    else:
                        n += 1

    def dopay():
        with open('goods.csv', 'w', newline='') as f:
            # 读取csv中商品信息并替换
            f_csv = csv.writer(f)
            global buyed
            f_csv.writerows(buyed)
        messagebox.showinfo("Tips", "支付成功！共支付{:.2f}元".format(pay))

    def clear():
        varid.set('')
        varunm.set('')

    tk.Button(window_buy, text="添加到购物车", font="微软雅黑", command=dobuy).place(x=30, y=120, height=40, width=200)
    Button(window_buy, text="清除", font="微软雅黑", command=clear).place(x=250, y=120, height=40, width=100)

    tree = ttk.Treeview(window_buy, columns=['name', 'out_price', 'num', 'count'], show="headings",
                        displaycolumns="#all", height=20)
    tree.place(x=30, y=170, height=250, width=450)
    tree.heading('name', text="商品名称")
    tree.heading('out_price', text="商品单价")
    tree.heading('num', text="购买数量")
    tree.heading('count', text="总价")
    tree.column('name', width=100, anchor=CENTER)
    tree.column('out_price', width=100, anchor=CENTER)
    tree.column('num', width=100, anchor=CENTER)
    tree.column('count', width=100, anchor=CENTER)

    Button(window_buy, text="支付", font="微软雅黑", command=dopay).place(x=370, y=430, height=40, width=100)
    # 创建一个滚动条控件，默认为垂直方向
    sbar1 = Scrollbar(window_buy)
    # 将滚动条放置在右侧，并设置当窗口大小改变时滚动条会沿着垂直方向延展
    sbar1.pack(side=RIGHT, fill=Y)
    # 创建水平滚动条，默认为水平方向,当拖动窗口时会沿着X轴方向填充
    sbar2 = Scrollbar(window_buy, orient=HORIZONTAL)
    sbar2.pack(side=BOTTOM, fill=X)
    # 使用 command 关联控件的 yview、xview方法
    sbar1.config(command=tree.yview)
    sbar2.config(command=tree.xview)

    window_buy.mainloop()


def add():
    def doadd():
        try:
            name = entryname.get()
            inprice = entryinprice.get()
            outprice = entryoutprice.get()
            discount = entrydiscount.get()
            inventory = entryinventory.get()
        except:
            messagebox.showinfo("Warning", "非法输入！")
        else:
            if len(name) == 0:
                messagebox.showinfo("Warning", "请输入数据！")
            else:
                n = 1
                with open('goods.csv', newline='')as f:
                    f_csv = csv.reader(f)
                    headers = next(f_csv)
                    for row in f_csv:
                        n += 1
                with open('goods.csv', 'a', newline='')as f:
                    f_csv = csv.writer(f)
                    f_csv.writerow([n, name, inprice, outprice, discount, inventory])
                messagebox.showinfo("Tips", "添加成功！")

    def clear():
        varname.set('')
        varinprice.set('')
        varoutprice.set('')
        vardiscount.set('')
        varinventory.set('')

    window_add = tk.Tk()
    user = login(window_add)
    width = 500
    height = 500
    window_add.title("进货")
    window_add.geometry("{:}x{:}".format(width, height))
    window_add.resizable(False, False)
    try:  # 因为用户可能直接关闭主窗口，所以我们要捕捉这个错误
        window_add.wait_window(window=user)  # 等待直到login销毁，不销毁后面的语句就不执行
        index(window_add)
    except:
        pass
    else:
        # 创建关联字符变量
        varname = IntVar(window_add, value='')
        varinprice = IntVar(window_add, value='')
        varoutprice = IntVar(window_add, value='')
        vardiscount = IntVar(window_add, value='')
        varinventory = IntVar(window_add, value='')

        # 创建标签组件
        Label(window_add, text="商品名称：", font="微软雅黑").place(x=30, y=10, height=40, width=100)
        Label(window_add, text="进货价：", font="微软雅黑").place(x=30, y=60, height=40, width=100)
        Label(window_add, text="售卖价：", font="微软雅黑").place(x=30, y=110, height=40, width=100)
        Label(window_add, text="折扣：", font="微软雅黑").place(x=30, y=160, height=40, width=100)
        Label(window_add, text="库存：", font="微软雅黑").place(x=30, y=210, height=40, width=100)

        # 创建文本框组件，同时设置关联的变量
        #    商品名称entryname
        #    商品进货价entryinprice
        #    商品售卖价entryoutprice
        #    商品折扣entrydiscount
        #    商品库存entryinventory
        entryname = Entry(window_add, textvariable=varname)
        entryname.place(x=150, y=10, height=40, width=200)
        entryinprice = Entry(window_add, textvariable=varinprice)
        entryinprice.place(x=150, y=60, height=40, width=200)
        entryoutprice = Entry(window_add, textvariable=varoutprice)
        entryoutprice.place(x=150, y=110, height=40, width=200)
        entrydiscount = Entry(window_add, textvariable=vardiscount)
        entrydiscount.place(x=150, y=160, height=40, width=200)
        entryinventory = Entry(window_add, textvariable=varinventory)
        entryinventory.place(x=150, y=210, height=40, width=200)
        # 创建按钮
        buttondoadd = tk.Button(window_add, text="添加", font="微软雅黑", command=doadd)
        buttondoadd.place(x=150, y=400, height=40, width=200)
        buttonclear = Button(window_add, text="清除", font="微软雅黑", command=clear)
        buttonclear.place(x=200, y=350, height=40, width=100)
        window_add.mainloop()


def change():
    def dochange():
        name = entryname.get()
        try:
            id = int(entryid.get())
        except:
            messagebox.showinfo("Warning", "非法输入！")
        else:
            inprice = entryinprice.get()
            outprice = entryoutprice.get()
            discount = entrydiscount.get()
            inventory = entryinventory.get()
            attribute = [id, name, inprice, outprice, discount, inventory]
            if not (inprice or outprice or discount or inventory):
                messagebox.showinfo("Warning", "请输入数据！")
            else:
                with open('goods.csv', newline='')as f:
                    # 读取csv中商品信息并创建类
                    f_csv = csv.reader(f)
                    goods = [row for row in f_csv]
                if id > len(goods) - 1:
                    messagebox.showinfo("Warning", "暂无该商品！")
                else:
                    n = 0
                    for good in goods:
                        if good[0] == str(id):
                            m = 0
                            for i in attribute:
                                if i:
                                    goods[n][m] = attribute[m]
                                    m += 1
                                else:
                                    m += 1
                            break
                        else:
                            n += 1
                    with open('goods.csv', 'w', newline='') as f:
                        # 读取csv中商品信息并创建类
                        f_csv = csv.writer(f)
                        f_csv.writerows(goods)
                messagebox.showinfo("Tips", "修改成功！")

    def clear():
        varid.set('')
        varid.set('')
        varname.set('')
        varinprice.set('')
        varoutprice.set('')
        vardiscount.set('')
        varinventory.set('')

    window_change = tk.Tk()
    window_change.title("商品信息修改")
    width = 500
    height = 500
    window_change.geometry("{:}x{:}".format(width, height))
    window_change.resizable(False, False)
    user = login(window_change)
    try:  # 因为用户可能直接关闭主窗口，所以我们要捕捉这个错误
        window_change.wait_window(window=user)  # 等待直到login销毁，不销毁后面的语句就不执行
        index(window_change)
    except:
        pass
    else:
        # 创建关联字符变量
        varid = IntVar(window_change, value='')
        varname = IntVar(window_change, value='')
        varinprice = IntVar(window_change, value='')
        varoutprice = IntVar(window_change, value='')
        vardiscount = IntVar(window_change, value='')
        varinventory = IntVar(window_change, value='')

        # 创建标签组件
        Label(window_change, text="商品编号：", font="微软雅黑").place(x=30, y=10, height=40, width=100)
        Label(window_change, text="商品名称：", font="微软雅黑").place(x=30, y=60, height=40, width=100)
        Label(window_change, text="进货价：", font="微软雅黑").place(x=30, y=110, height=40, width=100)
        Label(window_change, text="售卖价：", font="微软雅黑").place(x=30, y=160, height=40, width=100)
        Label(window_change, text="折扣：", font="微软雅黑").place(x=30, y=210, height=40, width=100)
        Label(window_change, text="库存：", font="微软雅黑").place(x=30, y=260, height=40, width=100)

        # 创建文本框组件，同时设置关联的变量
        #    商品名称entryname
        #    商品进货价entryinprice
        #    商品售卖价entryoutprice
        #    商品折扣entrydiscount
        #    商品库存entryinventory
        entryid = Entry((window_change), textvariable=varid)
        entryid.place(x=150, y=10, height=40, width=200)
        entryname = Entry(window_change, textvariable=varname)
        entryname.place(x=150, y=60, height=40, width=200)
        entryinprice = Entry(window_change, textvariable=varinprice)
        entryinprice.place(x=150, y=110, height=40, width=200)
        entryoutprice = Entry(window_change, textvariable=varoutprice)
        entryoutprice.place(x=150, y=160, height=40, width=200)
        entrydiscount = Entry(window_change, textvariable=vardiscount)
        entrydiscount.place(x=150, y=210, height=40, width=200)
        entryinventory = Entry(window_change, textvariable=varinventory)
        entryinventory.place(x=150, y=260, height=40, width=200)

        buttondoadd = tk.Button(window_change, text="更改", font="微软雅黑", command=dochange)
        buttondoadd.place(x=100, y=350, height=40, width=100)
        buttonclear = Button(window_change, text="清除", font="微软雅黑", command=clear)
        buttonclear.place(x=200, y=350, height=40, width=100)
        window_change.mainloop()


pay = 0
with open('goods.csv', newline='')as f:
    # 读取csv中商品信息
    f_csv = csv.reader(f)
    buyed = [row for row in f_csv]
# 调用Tk()创建主窗口
window = tk.Tk()
# 窗口名
window.title("商品管理系统")
# 设置窗口大小变量
width = 500
height = 500
# 设置窗口大小
window.geometry("{:}x{:}".format(width, height))
# 固定窗口大小
window.resizable(False, False)
# 更改窗口左上角图标
window.iconbitmap("logo.ico")
# 窗口居中，获取屏幕尺寸以计算布局参数，使窗口居屏幕中央
screenwidth = window.winfo_screenwidth()
screenheight = window.winfo_screenheight()
size_geo = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
window.geometry(size_geo)

# 添加文本内,设置字体的前景色和背景色，和字体类型、大小
tk.Label(window, text="欢迎使用商品管理系统", fg="black", font=('Times', 20, 'bold italic'), pady=20).pack()
# 添加按钮，以及按钮的文本，并通过command 参数设置窗口的功能
tk.Button(window, text="显示商品信息", font="微软雅黑", command=show).place(x=150, y=100, height=40, width=200)
tk.Button(window, text="购买商品", font="微软雅黑", command=buy).place(x=150, y=200, height=40, width=200)
tk.Button(window, text="修改商品信息", font="微软雅黑", command=change).place(x=150, y=300, height=40, width=200)
tk.Button(window, text="添加商品", font="微软雅黑", command=add).place(x=150, y=400, height=40, width=200)

window.mainloop()
